package com.lagou.rpc.provider.zk;

import com.alibaba.fastjson.JSONObject;
import com.lagou.rpc.provider.config.ServerIpPortProperties;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * zookeeper客户端
 *
 * @Author: zhangzhiwei
 * @Date: 2022/2/14 4:09 下午
 */
@Component
public class ProviderZk {

    @Autowired
    private ServerIpPortProperties ipPort;

    public void register() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                .connectString("192.168.229.131:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(retryPolicy)
                .namespace("rpc")
                .build();
        zkClient.start();
        // ip和端口注册到zk上
        Stat stat = zkClient.checkExists().forPath("/provider");
        if(stat == null){
            zkClient.create().creatingParentsIfNeeded().forPath("/provider");
        }
        // 将ip和端口转成json字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ip", ipPort.getIp());
        jsonObject.put("port", ipPort.getPort());
        jsonObject.put("usedTime", 0);
        jsonObject.put("requestTime", 0);
        zkClient.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath("/provider/p", jsonObject.toJSONString().getBytes());
        System.out.println("==========服务成功注册到zk==========");
    }

}
